import React from 'react';

  // 错误边界必须保持类组件形式
class ErrorBoundary extends React.Component<{children: React.ReactNode}, {hasError: boolean}> {
    state = { hasError: false };

    static getDerivedStateFromError() {
        return { hasError: true };
    }

    componentDidCatch(error: Error, _errorInfo: React.ErrorInfo) {
        if (window.pageObserver) {
            window.pageObserver.lazyReportBatch({
                type: 'error',
                subType: 'js',
                stack: error?.stack,
                pageUrl: window.location.href,
                startTime: performance.now(),
            });
        }
    }

    render() {
        return this.state.hasError 
            ? <div>Something went wrong. Please try again later.</div>
            : this.props.children;
    }
}

export default ErrorBoundary;